package com.huiyin.ui;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.api.URLs;
import com.huiyin.base.BaseActivity;
import com.huiyin.http.AsyncHttpClient;
import com.huiyin.http.BinaryHttpResponseHandler;
import com.huiyin.utils.DensityUtil;
import com.huiyin.utils.DeviceUtils;
import com.huiyin.utils.ImageManager;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.LogUtil;
import com.huiyin.utils.PreferenceUtil;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.EScenarioType;

public class StartActivity extends BaseActivity {

	private TextView version;
	
	private ImageView welcome;
	private File welcomeimgFlord;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		View view = View.inflate(this, R.layout.start, null);
		setContentView(view);
		LogUtil.i("", android.os.Build.MODEL + "==屏幕宽度=======" + DensityUtil.px2dip(this, DensityUtil.getScreenWidth(this)));

		//百度移动统计
		//StatService.setDebugOn(false);
		//友盟移动统计
		MobclickAgent.setDebugMode(false);
        // SDK在统计Fragment时，需要关闭Activity自带的页面统计，
        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
        MobclickAgent.openActivityDurationTrack(false);
        // MobclickAgent.setAutoLocation(true);
        // MobclickAgent.setSessionContinueMillis(1000);
        // MobclickAgent.startWithConfigure(
        // new UMAnalyticsConfig(mContext, "4f83c5d852701564c0000011", "Umeng", EScenarioType.E_UM_NORMAL));
        MobclickAgent.setScenarioType(mContext, EScenarioType.E_UM_NORMAL);

		//加载图片
		welcome = (ImageView) findViewById(R.id.welcome);
		welcomeimgFlord = StorageUtils.getOwnCacheDirectory(mContext, "/huiyinlehu/cache/welcome");
		if (welcomeimgFlord.listFiles().length > 0) {
			ImageManager.LoadWithServer("file:///"+welcomeimgFlord.listFiles()[0].getPath(), welcome);
		}else{
			Drawable drawable = getResources().getDrawable(R.drawable.welcome);
			welcome.setImageDrawable(drawable);
		}
		
		//获取图片服务器地址
		getPath();

		//发送设备信息
		sendMobileInfo();

		//显示版本号
		version = (TextView) findViewById(R.id.version);
		version.setText("v " + DeviceUtils.getVersionName(this));

		
		//等待3秒进入主界面
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				boolean isFirstStart = PreferenceUtil.getInstance(getApplicationContext()).isFirstStart();
				if (isFirstStart) {
					UIHelper.showWelcomeAc(mContext);
					finish();
				} else {
					UIHelper.showMainAc(mContext);
					finish();
				}
			}
		}, 3000);
	}
	
	
	/**
	 * 拿取图片路径处理
	 */
	private void getPath() {
		
		//将上次取得的图片服务器地址赋值到缓存
		String url = AppContext.getImageServer();
		URLs.setImageServer(url);
		
		CustomResponseHandler handler = new CustomResponseHandler(this, false) {
			@Override
			public void onRefreshData(String content) {
				if(isSuccessResponse(content)){
					
					String imgPath = JSONParseUtils.getString(content, "imgPath");
					String portPath = JSONParseUtils.getString(content, "portPath");
					LogUtil.i("StartActivity", "imgPath:"+imgPath);
					LogUtil.i("StartActivity", "portPath:"+portPath);
					
					//保存图片服务器地址
					URLs.setImageServer(imgPath);
					
					//获取启动页图片
					getImageView();
				}
			}
		};
		RequstClient.getPath(handler);
	}
	
	
	/**
	 * 获取启动页加载图
	 */
	private void getImageView() {
		CustomResponseHandler handler = new CustomResponseHandler(this, false) {
			@Override
			public void onRefreshData(String content) {
				try {
					JSONObject object = new JSONObject(content);
					JSONArray array = new JSONArray(object.getString("kaiji"));
					JSONObject jsonObject = array.getJSONObject(0);
					String[] str = jsonObject.getString("IMG").split("/");
					String FileName = str[str.length - 1];
					if (welcomeimgFlord.listFiles().length == 0 || !FileName.equals(welcomeimgFlord.list()[0])){
						downloadImage(jsonObject.getString("IMG"));
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		};
		RequstClient.appOpenPicture(handler);
	}

	/**
	 * 发送设备信息
	 */
	private void sendMobileInfo() {
		if (!PreferenceUtil.getInstance(getApplicationContext()).isSendMobileInfo()) {
			TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			String imei = tm.getDeviceId();
			CustomResponseHandler handler = new CustomResponseHandler(this, false) {
				@Override
				public void onRefreshData(String content) {
					try {
						JSONObject roots = new JSONObject(content);
						if (roots.getString("type").equals("1")) {
							PreferenceUtil.getInstance(getApplicationContext()).setSendMobileInfo(true);
						} else {
							return;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			};
			RequstClient.sendMobileInfo(imei, DeviceUtils.getVersionName(this), handler);
		}
	}
	
	/**
	 * 下载图片
	 * @param welcome_img
	 */
	private void downloadImage(String welcome_img) {
		final String imagename = welcome_img;
		welcome_img = URLs.IMAGE_URL + welcome_img;
		AsyncHttpClient client = new AsyncHttpClient();
		String[] allowedTypes = new String[] { "image/jpeg", "image/png" };
		client.get(welcome_img, new BinaryHttpResponseHandler(allowedTypes) {
			public void onSuccess(byte[] imageData) {
				if (imageData != null) {
					Bitmap mBitmap = BitmapFactory.decodeByteArray(imageData,
							0, imageData.length);// bitmap
					try {
						saveFile(mBitmap, imagename, mContext);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			@SuppressWarnings("unused")
			public void onFailure(Throwable e, byte[] imageData) {

			}
		});

	}

	public void saveFile(Bitmap bm, String fileName, Context mContext)
			throws IOException {
		String[] str = fileName.split("/");
		String FileName = str[str.length - 1];
		File file = new File(welcomeimgFlord,FileName);
		File[] list = file.getParentFile().listFiles();
		for (int i = 0; i < list.length; i++)
			list[i].delete();
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(file));
		bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		bos.flush();
		bos.close();
		bm.recycle();
	}
	
	
//	@Override
//	protected void onResume() {
//		super.onResume();
//		StatService.onResume(this);
//	}
//
//	@Override
//	protected void onPause() {
//		super.onPause();
//		StatService.onPause(this);
//	}
//	

}
